const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const readSetting = require("../../lib/read_setting");
const ffmpegPath = path.join(__dirname ,'../../', 'ffmpeg', 'ffmpeg.exe');

module.exports = (req, res) => {
    let { newname = '', outputPath, m3u8Path, keyPath, tsPath } = req.body;

    if (!newname) return res.send({ code: 400, msg: "请输入新文件名", result: "解密失败" });

    if (!fs.existsSync(outputPath)) {
        outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');
    };

    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }

    let filepath = path.join(outputPath, (newname + '.mp4'));

    if (fs.existsSync(filepath)) return res.send({ code: 400, msg: `${filepath} 已存在`, result: "解密失败" });

    if (!fs.existsSync(m3u8Path)) return res.send({ code: 400, msg: "m3u8文件不存在", result: "解密失败" });

    if (!fs.existsSync(keyPath)) return res.send({ code: 400, msg: "key文件不存在", result: "解密失败" });

    if (!fs.existsSync(tsPath)) return res.send({ code: 400, msg: "ts所在文件夹不存在", result: "解密失败" });


    let m3u8Data = fs.readFileSync(m3u8Path, 'utf8');

    let tempData = m3u8Data;

    keyPath = keyPath.replace(/\\+/g, "/");

    m3u8Data = m3u8Data.replace(/(,URI=)"(.+)"/, `$1"${keyPath}"`);

    m3u8Data = m3u8Data.split("\n");

    for (let i = 0; i < m3u8Data.length; i++) {
        if (/^#.+/.test(m3u8Data[i])) {
            continue;
        } else {
            if (m3u8Data[i]) {
                m3u8Data[i] = path.join(tsPath, m3u8Data[i]);
            } else {
                continue;
            }
        }
    }

    m3u8Data = m3u8Data.filter(v => v).join("\n");

    fs.writeFileSync(m3u8Path, m3u8Data, 'utf8');

    let cmd = `"${ffmpegPath}" -allowed_extensions ALL -i "${m3u8Path}" -c copy "${filepath}"`;

    exec(cmd, (err, stdout, stderr) => {
        fs.writeFileSync(m3u8Path, tempData, 'utf8');
        if (err) {
            console.log(err)
            return res.send({
                code: 400,
                msg: `${newname} 解密失败！`,
                result: `请检查你提供的参数是否正确！`,
                state: false
            })
        }

        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })

        res.send({
            code: 200,
            msg: `${newname} 解密成功！`,
            result: `文件保存在：${filepath}`,
            state: true
        });
    });

}